package com.hilihili.service.impl;

import cn.hutool.json.JSONUtil;
import com.hilihili.constant.RedisStaticResourceConstant;
import com.hilihili.domain.entity.District;
import com.hilihili.domain.entity.Tag;
import com.hilihili.domain.entity.Topic;
import com.hilihili.mapper.DistrictMapper;
import com.hilihili.service.IDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author machi
 * @date 2023/12/17
 */
@Service
public class DistrictServiceImpl implements IDistrictService {

    @Autowired
    DistrictMapper districtMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public List<District> getDistrict() {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        //先查缓存 命中则直接返回
        String firstLevelDistrict = opsForValue.get(RedisStaticResourceConstant.FIRST_LEVEL_DISTRICT);
        if (firstLevelDistrict != null) {
            return JSONUtil.toList(firstLevelDistrict, District.class);
        }
        //未命中 查询数据库 添加redis缓存
        List<District> district = districtMapper.getDistrict();
        opsForValue.set(RedisStaticResourceConstant.FIRST_LEVEL_DISTRICT, JSONUtil.toJsonStr(district));
        return district;
    }

    @Override
    public List<District> getDistrictItem(Integer parentId) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        Object secondLevelDistrict = opsForValue.get(RedisStaticResourceConstant.SECOND_LEVEL_DISTRICT + parentId);
        if (secondLevelDistrict != null) {
            return JSONUtil.toList(secondLevelDistrict.toString(), District.class);
        }
        List<District> districtItem = districtMapper.getDistrictItem(parentId);
        opsForValue.set(RedisStaticResourceConstant.SECOND_LEVEL_DISTRICT + parentId, JSONUtil.toJsonStr(districtItem));
        return districtItem;

    }

    @Override
    public List<Tag> getTag(String tag) {
        // TODO: 2023/12/18  需要调用es推荐算法推荐标签 redis 缓存
        String[] tags = tag.split(",");
        return districtMapper.getTag();
    }

    @Override
    public List<Topic> getTopic(String tag) {
        // TODO: 2023/12/18 需要调用es推荐算法推荐话题 redis 缓存
        return districtMapper.getTopic();
    }

    @Override
    public String getTopicByVideoId(Long id) {
        return districtMapper.getTopicByVideoId(id);
    }

    @Override
    public List<String> getTagByVideoId(Long id) {
        return districtMapper.getTagByVideoId(id);
    }
}
